
# Modified version of http://mail.python.org/pipermail/python-list/2004-May/260937.html
#Any code run here takes a performance hit because of the trace.
import sys
import trace
import threading

class KThread(threading.Thread):
	"""A subclass of threading.Thread, with a kill() method."""
	def __init__(self, fn, *args):
		threading.Thread.__init__(self)
		self.fn = fn
		self.args = args
		self.killed = False

	def start(self):
		"""Start the thread."""
		threading.Thread.start(self)

	def run(self):
		sys.settrace(self.globaltrace)
		self.fn(*self.args)

	def globaltrace(self, frame, why, arg):
		# only trace this scope.
		if why == 'call': return self.localtrace
		else: return None

	def localtrace(self, frame, why, arg):
		#~ print '?'
		if self.killed:
			if why == 'line':
				raise SystemExit()
		return self.localtrace

	def kill(self):
		self.killed = True